package com.cicadamob.contact.api.group.http;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.Logger.AppLogger;
import com.cicadamob.contact.api.group.bean.ResultModel;
/**
 * 群组相关http操作
 * @author mengxs
 *
 */
public class Http_Group_Util {
	
	public static String TAG="Http_Group_Util";
	/**是否需要发送短信   1发送  0 不发送**/
	public static final String needSendSms="1";
	
	public static final int BUFFER_SIZE = 1024 * 16; // stream缓冲大小
	public static final int ARRAY_SIZE = 1024 * 8; // 每次读取缓冲大小
	/**
	 * 获取错误信息
	 * @param retcode
	 * @return
	 */
	public static String getRetMsg(int retcode) {
		/**
		 * 0：成功 1：错误的请求参数 2：群组名已经存在 3：群组不存在 4：超过最大群组数 5：超过最大群组成员数 6：群组成员已经存在
		 * 7：群组成员不存在 8：无操作权限  -10网络异常  -8网络异常   -9网络超时
		 */
		String msg = "";
		switch (retcode) {
		case 0:
			msg = "操作成功";
			break;
		case 1:
			msg = "错误的请求参数";
			break;
		case 2:
			msg = "群组名已经存在 ";
			break;
		case 3:
			msg = "群组不存在 ";
			break;
		case 4:
			msg = "超过最大群组数";
			break;
		case 5:
			msg = "超过最大群组成员数";
			break;
		case 6:
			msg = "群组成员已经存在";
			break;
		case 7:
			msg = "群组成员不存在 ";
			break;
		case 8:
			msg = "无操作权限";
			break;
		case -9:
			msg = "网络超时，请重试";
			break;
		case -8:
			msg = "网络异常，请重试";
			break;
		case -10:
			msg = "网络异常，请重试";
			break;
		case 100:
			msg = "网络异常，请检查网络";
			break;
		case 101:
			msg = "创建成功，但网络异常没获取最新成员列表，请刷新获取最新群组列表";
			break;
		default:
			msg = "系统异常";
			break;
		}
		return msg;

	}
   /**
    * 获取请求xml的头部
    * @param userid
    * @param token
    * @param timestamp
    * @return
    */
	public static  String getRequestHeadXML(){
	String head_str="<msgheader>" 
				+ "<userid>"+ ContactConfig.getMobile(ContactConfig.getContext()) + "</userid>"			
				 + "<token>" + ContactConfig.getToken(ContactConfig.getContext())+"</token>"
				+ "<imei>" + ContactConfig.getIMEI(ContactConfig.getContext())+ "</imei>"
				+ "<imsi>" + ContactConfig.getIMSI(ContactConfig.getContext())+ "</imsi>"
				+ "<timestamp>" + System.currentTimeMillis()+""+ "</timestamp>"
				+ "</msgheader>";
		
		
	return head_str;
	}
	/**
	 * 编辑群组请求xml
	 * 
	 * @param userid
	 *            手机号码
	 * @param token
	 * @param timestamp
	 * @param groupid
	 *            组id
	 * @param groupname
	 *            组名称
	 * @param remark
	 *            组备注
	 * @param sms
	 *            是否短信通知群组成员。默认不发送通知。 取值范围： 0：不发送短信通知 1：发送短信通知
	 * 
	 * @return
	 */
	public static String get_modPersonalGroupXML(String groupid,
			String groupname,String remark,String imageInfo){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<groupid>" + groupid+ "</groupid>"
				+ "<groupname>" + groupname+ "</groupname>"
				+ "<remark>" + remark+ "</remark>"
				+ "<sms>" + needSendSms+ "</sms>"
				+ "<imageInfo>" + imageInfo+ "</imageInfo>"
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}

	/**
	 * 创建群组请求的xml
	 * 
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param groupname
	 * @param remark
	 * @param groupmembers
	 *            以JSON格式提供群组成员列表，包括群组成员手机号码(phone—手机号)、姓名（displayname）、是否短信通知(
	 *            sms，默认不发送通知。 取值范围： 0：不发送短信通知 1：发送短信通知 其他值为非法值。)
	 * 
	 * @return
	 */
	public static String get_createPersonalGroupXML(
			String groupname,String remark,String groupmembers,String imageInfo){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<groupname>" + groupname+ "</groupname>"
				+ "<remark>" + remark+ "</remark>"
				+ "<groupmembers>" + groupmembers+ "</groupmembers>"
				+ "<imageInfo>" + imageInfo+ "</imageInfo>"
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}
	/**
	 * 删除群组请求的xml
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param groupid
	 * @param sms
	 * @return
	 */
	public static String get_deletePersonalGroupXML(
			String groupid,String sms){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<groupid>" + groupid+ "</groupid>"
				+ "<sms>" + needSendSms+ "</sms>"
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}
	/**
	 * 获取群组列表请求的xml
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param lastupdatetime
	 * @return
	 */
	public static String get_getPersonalGroupXML(
			String lastupdatetime){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<lastupdatetime>" + lastupdatetime+ "</lastupdatetime>"
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}
	/**
	 * 添加成员的请求xml
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param groupid
	 * @param groupmembers
	 * @return
	 */
	public static String get_addGroupMemberXML(
			String groupid,String groupmembers){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<groupid>" + groupid+ "</groupid>"
				+ "<groupmembers>" + groupmembers+ "</groupmembers>"
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}
	/**
	 * 修改成员信息请求的xml
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param groupid
	 * @param memberid
	 * @param phone
	 * @param displayname
	 * @param company
	 * @param department
	 * @param jobprofession
	 * @param sms
	 * @return
	 */
	public static String get_modGroupMemberXML(
			String groupid,String memberid,String phone,String displayname ,String company,String department,
			String jobprofession,String sms){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<groupid>" + groupid+ "</groupid>"
				+ "<memberid>" + memberid+ "</memberid>"
				+ "<phone>" + phone+ "</phone>"
				+ "<displayname>" + displayname+ "</displayname>"
				+ "<company>" + company+ "</company>"
				+ "<department>" + department+ "</department>"
				+ "<jobprofession>" + jobprofession+ "</jobprofession>"
				+ "<sms>" + needSendSms+ "</sms>"
			 
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}
 
	/**
	 * 删除成员请求的xml
	 * 
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param groupid
	 * @param groupmembers
	 *            以JSON格式提供群组成员列表，包括群组成员id列表（memberlist）。 JSON样例： {
	 *            “memberlist”:[”111111”, ”22222”] }
	 * 
	 * @param sms
	 * @return
	 */
	public static String get_deleteGroupMemberXML(
			String groupid,String groupmembers,String sms){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<groupid>" + groupid+ "</groupid>"
				+ "<groupmembers>" + groupmembers+ "</groupmembers>"
				+ "<sms>" + needSendSms+ "</sms>"
				
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}
	/**
	 * 获取群组成员请求的xml
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param groupid
	 * @param lastupdatetime
	 * @return
	 */
	public static String get_getGroupMemberXML(
			String groupid,String lastupdatetime){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<groupid>" + groupid+ "</groupid>"
				+ "<lastupdatetime>" + lastupdatetime+ "</lastupdatetime>"
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}


	/**
	 * 解析返回结果
	 * @param resullt
	 * @return
	 */
	public static ResultModel parseResult(String result){
		
		 ResultModel model=new ResultModel();
		 if(result==null || "".equals(result)){
			 model.setRetcode(-8);
			 return model;
		 }
		 byte[] bytes=result.getBytes();
		 try {
			ByteArrayInputStream input = new ByteArrayInputStream(bytes);
				XmlPullParserFactory pull = XmlPullParserFactory.newInstance();
				pull.setNamespaceAware(true);
				XmlPullParser parser = pull.newPullParser();
				parser.setInput(input, "utf-8");
				int tagType = parser.getEventType();
				while (tagType != XmlPullParser.END_DOCUMENT) {
					if (tagType == XmlPullParser.START_TAG) {
						if ("retcode".equals(parser.getName())) {
							model.setRetcode(Integer.parseInt(parser.nextText()));
						} else if ("groupid".equals(parser.getName())) {
							model.setGroupid(parser.nextText());
						} else if ("groupmembers".equals(parser.getName())) {
							model.setGroupmembers(parser.nextText());
						}else if ("lastupdatetime".equals(parser.getName())) {
							model.setLastupdatetime(parser.nextText());
						}else if ("grouplist".equals(parser.getName())) {
							model.setGrouplist(parser.nextText());
						}else if ("installuser".equals(parser.getName())) {
							model.setInstalluser(parser.nextText());
						}else if ("imagePath".equals(parser.getName())) {
							model.setImagePath(parser.nextText());
						}
					}
					tagType = parser.next();
				}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return model;
		
	}
	
	/**
	 * 获取客户端安装状态
	 * 
	 * @param userlist
	 * @return
	 */
	public static  String getClientInstallStatusXML(Map<String, String> userlist) {
		String result = null;
		String strList = "";
		if (userlist != null && userlist.size() > 0) {
			try {
				JSONObject obj = new JSONObject();
				JSONArray array = new JSONArray();
				for (String phone : userlist.keySet()) {
					JSONObject itemobj = new JSONObject();
					itemobj.put("phone", phone);
					array.put(itemobj);
				}
				obj.put("userlist", array);
				strList = obj.toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<request>"
				+ "<body>" +getRequestHeadXML()

				+ "<msginfo>" + "<userlist>" + strList + "</userlist>"
				+ "</msginfo>"

				+ "</body>" + "</request>";
		return result;
	}
 
	/**
	 * 获取群组列表请求的xml
	 * @param userid
	 * @param token
	 * @param timestamp
	 * @param lastupdatetime
	 * @return
	 */
	public static String get_GroupAndMemberXML(
			String lastupdatetime){
		String result = null;
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<request>"
				+ "<body>"
				+getRequestHeadXML()
				
				+ "<msginfo>"
				+ "<lastupdatetime>" + lastupdatetime+ "</lastupdatetime>"
				+ "</msginfo>"
				
				+ "</body>"
				+ "</request>";
		return result;
	}
	
	public static String postCreateGroup(String xmlStr, String url,
			HttpURLConnection con) throws IOException, SocketTimeoutException {
        long time0 = System.currentTimeMillis();

		DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        AppLogger.d("请求url="+url+"\n\r " +
       		xmlStr);
    	AppLogger.writeLogToFile(ContactConfig.getContext(), ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "发送报文  url =" + url
	    		+"\r\n 传到服务器的xml ="+xmlStr, true);
		byte[] xmlStrBytes = xmlStr.getBytes();
		long time1 = System.currentTimeMillis();
		ds.write(gZip(xmlStrBytes));
		
		// ds.writeBytes(xmlStr);
		ds.flush();
		ds.close();
		int code = con.getResponseCode();
		if (code == 200) {
			long time3 = System.currentTimeMillis();
		 
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			 
			AppLogger.d(TAG,"服务器返回的xml = " + buffer.toString());
			AppLogger.writeLogToFile(ContactConfig.getContext(), ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "应答报文  url =" + url
		    		+"\r\n xml ="+buffer.toString(), true);
			return buffer.toString();
		}
		return null;
	}
	
	
	public static String postXML(String xmlStr, String url) throws IOException,
			SocketTimeoutException {
		URL tmpuri = new URL(url);
		if (tmpuri.getHost() == null)
			return null;
		if (tmpuri.getHost().compareTo("") == 0)
			return null;

		HttpURLConnection con = (HttpURLConnection) tmpuri.openConnection();
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		con.setRequestMethod("POST");
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty(
				"User-Agent",
				"Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
		// 链接超时
		con.setConnectTimeout(5000);
		DataOutputStream ds = new DataOutputStream(con.getOutputStream());
		byte[] xmlbytes = xmlStr.getBytes();
		if(url.endsWith("createPersonalGroupzip")){
			ds.write(gZip(xmlbytes));
		}else{
			ds.write(xmlbytes);
		}
	    AppLogger.writeLogToFile(ContactConfig.getContext(), ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "发送报文  url =" + url
	    		+"\r\n 传到服务器的xml ="+xmlStr, true);
		AppLogger.i(TAG, "请求url = " + url);
		AppLogger.d(TAG, "传到服务器的xml = " + xmlStr);
		// ds.writeBytes(xmlStr);
		ds.flush();
		ds.close();
		int code = con.getResponseCode();
		if (code == 200) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			AppLogger.i(TAG, "服务器返回的xml = " + buffer.toString());
			 AppLogger.writeLogToFile(ContactConfig.getContext(), ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "应答报文  url =" + url
			    		+"\r\n xml ="+buffer.toString(), true);
			return buffer.toString();
		}

		return null;
	}
	
	
	public static String postZipXML(String xmlStr, String url)
			throws IOException, SocketTimeoutException {
		URL tmpuri = new URL(url);
		if (tmpuri.getHost() == null)
			return null;
		if (tmpuri.getHost().compareTo("") == 0)
			return null;

		HttpURLConnection con = (HttpURLConnection) tmpuri.openConnection();
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		con.setRequestMethod("POST");
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty(
				"User-Agent",
				"Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
		// 链接超时
		con.setConnectTimeout(5000);
		DataOutputStream ds = new DataOutputStream(con.getOutputStream());
		ds.write(xmlStr.getBytes());
		// ds.writeBytes(xmlStr);
		AppLogger.d(TAG, "请求url = " + url);
		AppLogger.i(TAG, "传到服务器的xml = " + xmlStr);
 		ds.flush();
		ds.close();
		if (con.getResponseCode() == 200) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new GZIPInputStream(con.getInputStream(),
							BUFFER_SIZE)));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			AppLogger.i(TAG, "服务器返回的xml = " + buffer.toString());
			return buffer.toString();
		}

		return null;
	}
	
	
	
	public static byte[] gZip(byte[] data) {
		byte[] b = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(bos);
			gzip.write(data);
			gzip.finish();
			gzip.close();
			b = bos.toByteArray();
			bos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return b;
	}
}
